package edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer;

import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;

import edu.cs.usask.ca.silver.plugin.rcp.Activator;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverTreeObject;
import edu.cs.usask.ca.silver.plugin.rcp.editors.InfoEditor;
import edu.cs.usask.ca.silver.plugin.rcp.editors.InfoEditorInput;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;

public class ProjectViewDoubleClickListener implements IDoubleClickListener {

	private final ProjectViewI projectView;
	private IWorkbenchPage page;
	private static Logger logger = Logger.getLogger(ProjectViewDoubleClickListener.class);

	public ProjectViewDoubleClickListener(ProjectViewI projectViewer,
			IWorkbenchPage page) {
		this.projectView = projectViewer;
		this.page = page;

	}

	/**
	 * A method that implements the functionality associated with a double click
	 */
	public void doubleClick(DoubleClickEvent event) {

		IStructuredSelection selection = (IStructuredSelection) event
				.getSelection();
		SilverTreeObject treeObject = (SilverTreeObject) selection
				.getFirstElement();

		InfoEditorInput input = new InfoEditorInput(treeObject, projectView);

		input.addPropertyChangeListener(projectView);

		
		if (page == null) {
			logger.info("Page is null");
			page = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
		}

		try {

			page.openEditor(input, InfoEditor.ID);

			// Expand to next (1) level if current selection has children
			if (projectView.getTreeViewer().isExpandable(treeObject))
				projectView.getTreeViewer().expandToLevel(treeObject, 1);

		} catch (PartInitException e) {
			LoggerReportScheduler.scheduleErrorLogging(logger,"error in ProjectDoubleClickListener", e);
		}

	}/* end of doubleClick */

}
